import { defineStore } from 'pinia'
import { searchGlobal } from '@/api/search'

export const useSearchStore = defineStore('search', {
    state: () => ({
        searchResults: {},
        searchLoading: false,
        searchHistory: []
    }),

    actions: {
        // 全局搜索
        async searchGlobalAction(params) {
            this.searchLoading = true
            try {
                const response = await searchGlobal(params)
                if (response.code === 0) {
                    return response.data
                } else {
                    throw new Error(response.msg || '搜索失败')
                }
            } catch (error) {
                console.error('搜索失败:', error)
                throw error
            } finally {
                this.searchLoading = false
            }
        },

        // 添加搜索历史
        addSearchHistory(keyword) {
            if (!keyword.trim()) return

            // 移除重复的历史记录
            this.searchHistory = this.searchHistory.filter(item => item !== keyword)

            // 添加到开头
            this.searchHistory.unshift(keyword)

            // 限制历史记录数量
            if (this.searchHistory.length > 10) {
                this.searchHistory = this.searchHistory.slice(0, 10)
            }

            // 保存到本地存储
            localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory))
        },

        // 从本地存储加载搜索历史
        loadSearchHistory() {
            const history = localStorage.getItem('searchHistory')
            if (history) {
                this.searchHistory = JSON.parse(history)
            }
        },

        // 清空搜索历史
        clearSearchHistory() {
            this.searchHistory = []
            localStorage.removeItem('searchHistory')
        }
    }
})